#!/bin/bash

# Breeze Admin 健康检查脚本
# 作者: System Admin
# 日期: $(date +%Y-%m-%d)

set -e

# 配置变量
DEPLOY_DIR="/Users/shouzhi/techzhi/project/gitee/jar-deploy"
SERVICE_NAME="breeze-admin"
PID_FILE="$DEPLOY_DIR/${SERVICE_NAME}.pid"
HEALTH_URL="http://localhost:34080/actuator/health"
LOG_FILE="$DEPLOY_DIR/logs/health-check.log"

# 确保日志目录存在
mkdir -p "$(dirname "$LOG_FILE")"

# 记录检查时间
echo "$(date '+%Y-%m-%d %H:%M:%S') - 开始健康检查" >> "$LOG_FILE"

# 检查进程状态
if [ -f "$PID_FILE" ]; then
    PID=$(cat "$PID_FILE")
    if ps -p "$PID" > /dev/null 2>&1; then
        echo "进程运行正常 (PID: $PID)" >> "$LOG_FILE"
    else
        echo "错误: 进程不存在 (PID: $PID)" >> "$LOG_FILE"
        exit 1
    fi
else
    echo "错误: PID文件不存在" >> "$LOG_FILE"
    exit 1
fi

# 检查HTTP健康端点
if command -v curl > /dev/null 2>&1; then
    HTTP_STATUS=$(curl -s -o /dev/null -w "%{http_code}" "$HEALTH_URL" || echo "000")
    if [ "$HTTP_STATUS" = "200" ]; then
        echo "HTTP健康检查通过" >> "$LOG_FILE"
    else
        echo "错误: HTTP健康检查失败 (状态码: $HTTP_STATUS)" >> "$LOG_FILE"
        exit 1
    fi
else
    echo "警告: curl命令不可用，跳过HTTP健康检查" >> "$LOG_FILE"
fi

# 检查日志文件
LOG_DIR="$DEPLOY_DIR/logs"
if [ -d "$LOG_DIR" ]; then
    LOG_SIZE=$(du -s "$LOG_DIR" | cut -f1)
    if [ "$LOG_SIZE" -gt 1048576 ]; then  # 1GB
        echo "警告: 日志目录过大 (${LOG_SIZE}KB)" >> "$LOG_FILE"
    fi
else
    echo "错误: 日志目录不存在" >> "$LOG_FILE"
    exit 1
fi

echo "$(date '+%Y-%m-%d %H:%M:%S') - 健康检查完成" >> "$LOG_FILE"
echo "健康检查通过"
